import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { Layout, Breadcrumb } from 'antd';
import axios from './utils/axios';
import Header from './components/layout/header'
import SideMenu from './components/layout/sideMenu';
import Loader from './components/loader';
import './App.less';

const { Content, Footer } = Layout;

class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      spinning: false
    }
  }

  componentWillMount = () => {
    const { pathname } = this.props.location;
    if (!pathname.includes('/register')) {
      this.checkLogin();
    }
  }

  /*
  * 除了登录、注册页面不需要检测登录状态外，都需要调用接口判断当前的用户登录状态
  * 验证用户的登录状态后，根据当前所处的不同的页面作不同的跳转处理
  * */
  checkLogin = async () => {
    this.setState({spinning: true})
    const { pathname } = this.props.location;
    const isLoginPage = '/login' === pathname;
    const isIndex = '/' === pathname;
    try{
      const response = await axios.post('/api/principal');
      const { success } = response.data;
      if (success) {
        if (isLoginPage || isIndex) {
          this.props.history.push('/dashboard');
        }
      } else if(!isLoginPage){
        this.props.history.push('/login');
      }
    } catch (err) {
      if(!isLoginPage){
        this.props.history.push('/login');
      }
    }
    this.setState({spinning: false})
  }

  /*
  * 如果当前路由是登录页面，或者是注册页面的路由，则返回全页面
  * 如果是系统内页面，则返回包含有页头，侧边栏的布局结构
  * */
  render() {
    const { pathname } = this.props.location;
    if ('/login' === pathname || pathname.includes('/register')) {
      return (
          <div>
            <Loader spinning={ this.state.spinning } />
            { this.props.children }
          </div>
      )
    }
    return (
        <Layout>
          <Loader spinning={ this.state.spinning } />
          <SideMenu />
          <Layout className="layout">
            <Header />
            <Content className="layout-content">
              <Breadcrumb className="layout-bread">
                <Breadcrumb.Item>User</Breadcrumb.Item>
                <Breadcrumb.Item>Bill</Breadcrumb.Item>
              </Breadcrumb>
              <div className="layout-index">
                { this.props.children }
              </div>
            </Content>
            <Footer style={{ textAlign: 'center' }}>
              Copyright ©2018 云集智造
            </Footer>
          </Layout>
        </Layout>
    );
  }
}

export default withRouter(App);
